import { ref, onMounted, onUnmounted } from 'vue'
export const useCloseSelect = (scrollClassList: string[]) => {
	const timer2 = ref<number>()
	const closeSelect = (e: Event) => {
		const isElSelectScroll = (e.target as HTMLElement).closest('.el-select-dropdown__wrap');
		if (isElSelectScroll) {
			// 如果是 el-select 组件内部滚动，则不关闭下拉框
			return;
		}

		window.clearTimeout(timer2.value)
		timer2.value = window.setTimeout(() => {
			const elSelects = document.querySelectorAll('.el-popper');
			elSelects.forEach((elSelect: HTMLDivElement) => {
				elSelect.style.display = 'none'
			})
			const antdSelects = document.querySelectorAll('.ant-select-dropdown')
			antdSelects.forEach((antdSelect: HTMLDivElement) => {
				antdSelect.style.display = 'none'
			})
		}, 10)
	}
	const bindScroll = () => {
		scrollClassList.forEach((item) => {
			const currElement = document.querySelectorAll(item);
			currElement.forEach(item => {
				console.log(item.className)
				if (item.className.includes('el-select-dropdown__wrap') || item.getAttribute('isBind') === 'bind') {
					return
				}
				item.setAttribute('isBind', 'bind')
				item.addEventListener('scroll', closeSelect)
			})
		})
	}
	const removeBindScroll = () => {
		scrollClassList.forEach((item) => {
			const currElement = document.querySelectorAll(item);
			currElement.forEach(item => {
				item.removeEventListener('scroll', closeSelect)
				item.removeAttribute('isBind')
			})
		})
	}
	onMounted(bindScroll)
	onUnmounted(removeBindScroll)
	return {
		bindScroll,
		closeSelect,
		removeBindScroll
	}
}
